<template>
    <van-nav-bar title="雀神争霸" />

    <van-form @submit="onSubmit">
        <van-cell-group inset>
            <van-field
            v-model="username"
            name="用户名"
            placeholder="请输入用户名"
            />
            <van-field
            v-model="password"
            type="password"
            name="密码"
            placeholder="请输入用密码"
            />
        </van-cell-group>
        <div style="margin: 16px;">
            <van-button round block type="primary" native-type="submit">
            决战到天亮
            </van-button>
        </div>
    </van-form>
</template>

<script>
 import { ref, onMounted  } from 'vue';
 import { useRouter } from 'vue-router'; // 导入 useRouter 钩子
 import { post } from '../../utils/request';



export default {
    setup() {
        const username = ref('');
        const password = ref('');
        const router = useRouter(); // 获取 router 实例
         // 检查 token 并在存在时跳转
        const checkTokenAndRedirect = () => {
            const token = localStorage.getItem('token');
            if (token) {
                router.push('/');
            }
        };

        // // 在组件挂载时检查 token
        onMounted(() => {
            checkTokenAndRedirect();
        });

        const onSubmit = async () => {
            try {
                const result = await post('/api/anon/login', {
                    username: username.value,
                    password: password.value
                });
                console.log('登录成功', result);
                // 处理登录成功逻辑，如保存 token
                localStorage.setItem('token', result.data.token);
                router.push('/');
            } catch (error) {
                console.error('登录失败', error);
            }
        };
        return {
            username,
            password,
            onSubmit,
        };
    },
};

</script>